package com.zzyl.nursing.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zzyl.common.utils.SecurityUtils;
import com.zzyl.nursing.domain.AlertData;
import com.zzyl.nursing.dto.AlertDataHandleDto;
import com.zzyl.nursing.mapper.AlertDataMapper;
import com.zzyl.nursing.mapper.DeviceMapper;
import com.zzyl.nursing.service.IAlertDataService;
import com.zzyl.system.service.ISysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.List;

/**
 * 报警数据Service业务层处理
 *
 * @author ruoyi
 * @date 2025-09-27
 */
@Service
public class AlertDataServiceImpl extends ServiceImpl<AlertDataMapper, AlertData> implements IAlertDataService {
    @Autowired
    private AlertDataMapper alertDataMapper;

    @Autowired
    private DeviceMapper deviceMapper;

    /**
     * 查询报警数据
     *
     * @param id 报警数据主键
     * @return 报警数据
     */
    @Override
    public AlertData selectAlertDataById(Long id) {
        return alertDataMapper.selectById(id);
    }

    /**
     * 查询报警数据列表
     *
     * @param alertData 报警数据
     * @return 报警数据
     */
    @Override
    public List<AlertData> selectAlertDataList(AlertData alertData) {
        //获取当前用户id
        Long currentUserId = SecurityUtils.getUserId();
        if (currentUserId == null) {
            throw new RuntimeException("获取当前用户id失败");
        }

        if (!SecurityUtils.hasPermi("admin")) {
            //非管理只能看见自己负责老人的报警数据
            alertData.setUserId(currentUserId);
        }
        //管理员能看见所有报警数据
        return alertDataMapper.selectAlertDataList(alertData);
    }

    /**
     * 新增报警数据
     *
     * @param alertData 报警数据
     * @return 结果
     */
    @Override
    public int insertAlertData(AlertData alertData) {
        return alertDataMapper.insert(alertData);
    }

    @Autowired
    private ISysUserService sysUserService;

    /**
     * 修改报警数据
     *
     * @param
     * @return 结果
     */
    @Override
    public boolean updateAlertData(AlertDataHandleDto dto) {
        // 参数校验
        if (dto == null || dto.getId() == null) {
            throw new IllegalArgumentException("报警数据处理参数或ID不能为空");
        }
        log.debug("处理报警数据: " + dto);

        //获取当前请求对应用户id
        Long currentUserId = SecurityUtils.getUserId();
        if (currentUserId == null) {
            throw new RuntimeException("获取当前用户id失败");
        }
        //获取当前用户姓名
        String userName = sysUserService.selectUserById(currentUserId).getUserName();

        //根据根据iotid得到得到对应护工的userId集合,通过userId集合确定需要修改的报警数据
        AlertData currentAlertData = selectAlertDataById(dto.getId());
        if (currentAlertData == null) throw new RuntimeException("未找到id对应的报警数据");
        //判断报警数据是否已处理
        if (currentAlertData.getStatus().equals(1)) throw new RuntimeException("报警数据已处理");
        //根据id确定对应数据的位置类型
        Integer locationType = currentAlertData.getLocationType();
        List<Long> userIds = null;
        if (locationType == 0) {
            //随身
            userIds = deviceMapper.selectNursingIdsByIotIdWithElder(currentAlertData.getIotId());
        } else if (locationType == 1) {
            //固定
            userIds = deviceMapper.selectNursingIdsByIotIdWithBed(currentAlertData.getIotId());
        }
        if (userIds == null || userIds.isEmpty()) throw new RuntimeException("未找到iotid对应老人的的护工");
        //MyBatis-Plus 批量更新已内置事务支持

        //当status为1时不再能修改
        return lambdaUpdate()
                .in(AlertData::getUserId, userIds)
                .set(AlertData::getStatus, 1)
                .set(AlertData::getProcessorId, currentUserId)
                .set(AlertData::getProcessorName, userName)
                .set(AlertData::getProcessingTime, dto.getProcessingTime())
                .set(AlertData::getProcessingResult, dto.getProcessingResult())
                .update();

    }

    /**
     * 批量删除报警数据
     *
     * @param ids 需要删除的报警数据主键
     * @return 结果
     */
    @Override
    public int deleteAlertDataByIds(Long[] ids) {
        return alertDataMapper.deleteBatchIds(Arrays.asList(ids));
    }

    /**
     * 删除报警数据信息
     *
     * @param id 报警数据主键
     * @return 结果
     */
    @Override
    public int deleteAlertDataById(Long id) {
        return alertDataMapper.deleteById(id);
    }


}
